package service.impl;

import com.alibaba.fastjson.JSONObject;
import entity.inte.ResponseData;
import entity.inte.mycloud.folder.CreateFolderRequest;
import entity.inte.mycloud.folder.CreateFolderResponse;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import service.FolderService;
import session.SessionData;

import java.io.IOException;
import java.util.HashMap;

public class FolderServiceImpl implements FolderService {
	private static final Logger LOGGER = Logger.getLogger(FolderServiceImpl.class.getName());
	private static FolderService INSTANCE;
	public static final String CREATE_FOLDER_URL = "https://open.feishu.cn/open-apis/drive/v1/files/create_folder";
	/** 需要进行重试的错误码及描述映射 */
	public static final HashMap<Integer, String> ERR_CODE = new HashMap<>();


	private FolderServiceImpl() {
		ERR_CODE.put(233523001, "飞书未知错误");
	}

	public static FolderService getInstance() {
		if (INSTANCE == null)
			INSTANCE = new FolderServiceImpl();
		return INSTANCE;
	}

	@Override
	public CreateFolderResponse createFolder(CreateFolderRequest createFolderRequest) {
		LOGGER.info("创建文件夹请求体\n" + JSONObject.toJSONString(createFolderRequest));
		String authorization = SessionData.getAppAccessToken().getAuthorization();
		try {
			String jsonData = Jsoup.connect(CREATE_FOLDER_URL)
					.header("Authorization", authorization) //cookie
					.header("Content-Type", "application/json; charset=utf-8")
					.requestBody(JSONObject.toJSONString(createFolderRequest))
					.timeout(60000)
					.ignoreContentType(true)
					.ignoreHttpErrors(true)
					.post()
					.text();

			ResponseData<CreateFolderResponse> createFolderResponseResponseData = ResponseData.parseObject(jsonData, CreateFolderResponse.class);
			LOGGER.info("创建文件夹响应体\n" + JSONObject.toJSONString(createFolderResponseResponseData));
			if (createFolderResponseResponseData.getCode() != 0) {
				String msg = ERR_CODE.get(createFolderResponseResponseData.getCode());
				if (msg != null) {
					LOGGER.warn("创建文件夹失败，" + msg + "，进行重试");
					// 文件夹创建失败，这里进行重试
					return createFolder(createFolderRequest);
				}
			}

			return createFolderResponseResponseData.getData();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
